package com.huawei.aiosproj.engine;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.huawei.aiosproj.R;
import com.huawei.aiosproj.guiagent.GUIAgentEngine;
import com.huawei.aiosproj.utils.AssetsUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LLMEngineBasic extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 0;
    private static final int ACCESSIBILITY_REQUEST_CODE = 1;
    private static final String TAG = "LLMEngineBasic";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guiagent);

        File dir = getDir("models", Context.MODE_PRIVATE);
        String path = dir.getAbsolutePath() + File.separator;
        AssetManager assetManager = getAssets();
        // Init vsr models
        String modelName = "example.png";
        if (!AssetsUtils.isResourcesExist(modelName, path)) {
            AssetsUtils.copyResourcesToAppDir(assetManager, modelName, path);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAndRequestPermissions();
        Log.e(TAG, "onResume: " + "开始执行推理：");
        LLMRequest();
    }

    private void checkAndRequestPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.INTERNET);
        }

        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsToRequest.toArray(new String[0]), PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissonGranted = true;
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    allPermissonGranted = false;
                    break;
                }
            }
            if (allPermissonGranted) {
                Log.e(TAG, "onRequestPermissionsResult: " + "开始推理");
                LLMRequest();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void LLMRequest() {
        String apiKey = "7be3f2f1-1d29-4024-9aae-6153e261d5d9"; // 替换为实际API密钥
        String imageUrl = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"; // 图片URL

        new Thread(() -> {
            try {
                LLMEngineRequest client = new LLMEngineRequest(this, apiKey);
                File dir = getDir("models", Context.MODE_PRIVATE);
                String path = dir.getAbsolutePath() + File.separator;

                String response = client.runModel(path + "example.png", "帮我打开设置");
                String parseActionOutput = "";
//                String parseActionOutput =client.parseActionOutput(response);
                Log.e(TAG, "LLMRequest: " + response);
                Log.e(TAG, "LLM parseActionOutput request: " + parseActionOutput);
                JSONObject jsonObject = new JSONObject(parseActionOutput);
                String action = jsonObject.optString("action");
                Log.e(TAG, "Action: " + action);
                if (action.equals("click")) {
//                    List<Integer> coors = client.parseClickAction(parseActionOutput);
//                    Log.e(TAG, "LLMRequest coor: " + coors.get(0));
//                    Log.e(TAG, "LLMRequest coor: " + coors.get(1));
                }

            } catch (IOException | JSONException e) {
                e.printStackTrace();
                runOnUiThread(() -> Toast.makeText(this, "请求失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }
}
